﻿using System.IO;
using UnityEditor;
using UnityEditor.Build;
using UnityEditor.Build.Reporting;
using UnityEngine;

namespace Super
{
	public class BuildHandle : IPostprocessBuildWithReport
	{
		public int callbackOrder => 0;

		/// <summary>
		/// 打包前处理回调的方法
		/// </summary>
		public void OnPostprocessBuild(BuildReport report)
		{
			TryCreateLangAsset(report);
		}

		public bool TryCreateLangAsset(BuildReport report)
		{
			string buildPath = Path.GetDirectoryName(report.summary.outputPath);
			string LangDire = Path.Combine(buildPath, "Lang");
			string LangReadMePath = Path.Combine(LangDire, "ReadMe.txt");
			string LangKeyPath = Path.Combine(LangDire, "Keys.txt");
			bool isWindow64 = report.summary.platform == BuildTarget.StandaloneWindows64;
			bool isWindow = report.summary.platform == BuildTarget.StandaloneWindows;
			bool hasDirectory = Directory.Exists(LangDire);
			bool hasLangReadMe = File.Exists(LangReadMePath);
			bool hasLangKey = File.Exists(LangKeyPath);


			if (!isWindow64 && !isWindow)
			{
				return false;
			}

			if (!hasDirectory)
			{
				Directory.CreateDirectory(LangDire);
				Debug.Log($"创建{LangDire}目录");
			}
			if (!hasLangReadMe)
			{
				string assetPath = AssetDatabase.GetAssetPath(AssetSettingSO.Ins.templateLangReadMe);
				if (!string.IsNullOrEmpty(assetPath))
				{
					string absolutePath = GlobalUtil.GetAbsolutePath(assetPath);
					File.Copy(absolutePath, LangReadMePath);
					Debug.Log($"创建{LangReadMePath}文件");
				}
			}
			if (!hasLangKey)
			{
				string assetPath = PathSettingSO.Ins.langKeysPath;
				if (!string.IsNullOrEmpty(assetPath))
				{
					string absolutePath = GlobalUtil.GetAbsolutePath(assetPath);
					File.Copy(absolutePath, LangKeyPath);
					Debug.Log($"创建{LangKeyPath}文件");
				}
			}
			return true;
		}
	}
}
